﻿/***************************
 * 1.线路列表
 * 2.线路详情
 * 3.线路预订
 ****************************/

/* 变量 */
var line = "booking/line.html";
var lineDetail = "booking/lineDetail.html";
var lineBooking = "booking/lineBooking.html";
var linePay = "booking/linePay.html";

var tour_line = "elements/tour_line.html";
var tour_line_detail = "elements/tour_line_detail.html";

/***********    地图使用公共方法    **********/
//地图跳转-类似周边，跳转景区，要iframe能使用
function MapClickJump(url, param) {
    mainView.router.loadPage({ url: url, reload: false });
}
//调用语音接口，返回给子界面--地图使用
var voice = {
    localId: '',
    serverId: ''
};
function ReturnStartVoice() {
    wx.startRecord({
        cancel: function () {
            alert('用户拒绝授权录音');
        }
    });
};
function ReturnEndVoid(callback) {
    wx.stopRecord({
        success: function (res) {
            voice.localId = res.localId;
            wx.translateVoice({
                localId: voice.localId, // 需要识别的音频的本地Id，由录音相关接口获得
                isShowProgressTips: 1, // 默认为1，显示进度提示
                success: function (res) {
                    if (res.translateResult != 'undefined' && res.translateResult != '') {
                        yy = res.translateResult.replace(/['",.!?，。？！]/ig, ""); // 语音识别的结果
                        callback(yy);
                    }
                }
            });
        },
        fail: function (res) {
            alert(JSON.stringify(res));
        }
    });
};
//语音按钮事件
/* 初始化语音config */
var gn = ['startRecord', 'stopRecord', 'translateVoice', 'openLocation', 'getLocation'];
wx_config(gn, function () {
    //callback 所有JSSDK事件
}, function () {
    //errorcallback  config注册失败事件
});
/***********    地图使用公共方法----结束    **********/

/* 线路列表 */
var contactsCallback_line = myApp.onPageInit('line', function (page) {

    // 过滤 全部美食显示
    $$(".navbar-inner .right img").show();

    
        $$("#category_list ul li").hide();
        $$("#sel_line_price_range").show();
        $$("#sel_line_days").show();
    

    calendarLineIn = myApp.calendar({
        input: '#calendar-line-in',
        minDate: new Date(),
        maxDate: null,
        onClose: function (p) {
            if (calendarLineIn.length > 0)
                calendarLineOut.minDate = calendarLineIn.value[0];
        }
    });
    calendarLineOut = myApp.calendar({
        input: '#calendar-line-out',
        minDate: new Date(),
        onClose: function (p) {
            if (calendarLineOut.length > 0)
                calendarLineIn.maxDate = calendarLineOut.value[0];
        }
    });

    pickerLinePriceRange = myApp.picker({
        input: '#sel_line_price_range_value',
        toolbarTemplate:
        '<div class="toolbar theme-red">' +
        '<div class="toolbar-inner">' +
        '<div class="left"></div>' +
        '<div class="right">' +
        '<a href="#" class="link close-picker">确定</a>' +
        '</div>' +
        '</div>' +
        '</div>',
        formatValue: function (p, values, displayValues) {
            return displayValues;
        },
        cols: [
            {
                textAlign: 'center',
                values: (function () {
                    var arrValue = [];
                    $$.each(iss_dictionaryBaseData.linePriceRange(), function (i, obj) {
                        arrValue.push(obj.value);
                    });
                    return arrValue;
                })(),
                displayValues: (function () {
                    var arrDisplay = [];
                    $$.each(iss_dictionaryBaseData.linePriceRange(), function (i, obj) {
                        arrDisplay.push(obj.display);
                    });
                    return arrDisplay;
                })()
            }
        ]
    });

    pickerLineType = myApp.picker({
        input: '#sel_line_type_value',
        toolbarTemplate:
        '<div class="toolbar theme-red">' +
        '<div class="toolbar-inner">' +
        '<div class="left"></div>' +
        '<div class="right">' +
        '<a href="#" class="link close-picker">确定</a>' +
        '</div>' +
        '</div>' +
        '</div>',
        formatValue: function (p, values, displayValues) {
            return displayValues;
        },
        cols: [
            {
                textAlign: 'center',
                values: (function () {
                    var arrValue = [];
                    $$.each(iss_dictionaryBaseData.lineType(), function (i, obj) {
                        arrValue.push(obj.value);
                    });
                    return arrValue;
                })(),
                displayValues: (function () {
                    var arrDisplay = [];
                    $$.each(iss_dictionaryBaseData.lineType(), function (i, obj) {
                        arrDisplay.push(obj.display);
                    });
                    return arrDisplay;
                })()
            }
        ]
    });

    pickerLineDays = myApp.picker({
        input: '#sel_line_days_value',
        toolbarTemplate:
        '<div class="toolbar theme-red">' +
        '<div class="toolbar-inner">' +
        '<div class="left"></div>' +
        '<div class="right">' +
        '<a href="#" class="link close-picker">确定</a>' +
        '</div>' +
        '</div>' +
        '</div>',
        formatValue: function (p, values, displayValues) {
            return displayValues;
        },
        cols: [
            {
                textAlign: 'center',
                values: (function () {
                    var arrValue = [];
                    $$.each(iss_dictionaryBaseData.lineDays(), function (i, obj) {
                        arrValue.push(obj.value);
                    });
                    return arrValue;
                })(),
                displayValues: (function () {
                    var arrDisplay = [];
                    $$.each(iss_dictionaryBaseData.lineDays(), function (i, obj) {
                        arrDisplay.push(obj.display);
                    });
                    return arrDisplay;
                })()
            }
        ]
    });

    //删除滚动后重新添加滚动
    var flag_InfiniteScroll = true;
    //是否需要滚动加载
    var flag_needScroll = true;
    //滚动事件只执行一次
    var flag_execute = false;

    var index_tab1 = 1;
    var index_tab2 = 1;
    var index_tab3 = 1;
    var current_tabindex = 0;
    var size = 10;

    LoadLineAll(index_tab1, size);

    //加载数据
    function LoadLineAll(pageindex, pagesize) {

        // 检索条件
        var v_search = [];
        var v_order = [];

        //查询条件
        // 站点
        if (_cityCode != "") {
            var opt = {
                SearchField: "CityCode",
                ConditionType: 1,
                AndOR: "and",
                ListSearchValue: [
                    {
                        ItemValue: _cityCode
                    }
                ]
            };
            v_search.push(opt);
        }

        //价格
        if (pickerLinePriceRange && pickerLinePriceRange.value && pickerLinePriceRange.value.length > 0) {
            var opt = {
                SearchField: "PriceRange",
                ConditionType: 1,
                AndOR: "and",
                ListSearchValue: [
                    {
                        ItemValue: pickerLinePriceRange.value[0]
                    }
                ]
            };
            v_search.push(opt);
        }

        //线路类型
        if (pickerLineType && pickerLineType.value && pickerLineType.value.length > 0) {
            var opt = {
                SearchField: "LineStyle",
                ConditionType: 1,
                AndOR: "and",
                ListSearchValue: [
                    {
                        ItemValue: pickerLineType.value[0]
                    }
                ]
            };
            v_search.push(opt);
        }

        //开始时间
        if (calendarLineIn && calendarLineIn.value && calendarLineIn.value.length > 0) {
            var opt = {
                SearchField: "PlayEarlyDate",
                ConditionType: 1,
                AndOR: "and",
                ListSearchValue: [
                    {
                        ItemValue: calendarLineIn.input.val()
                    }
                ]
            };
            v_search.push(opt);
        }

        //结束时间
        if (calendarLineOut && calendarLineOut.value && calendarLineOut.value.length > 0) {
            var opt = {
                SearchField: "PlayLateDate",
                ConditionType: 1,
                AndOR: "and",
                ListSearchValue: [
                    {
                        ItemValue: calendarLineOut.input.val()
                    }
                ]
            };
            v_search.push(opt);
        }

        //出行天数
        if (pickerLineDays && pickerLineDays.value && pickerLineDays.value.length > 0) {
            var opt = {
                SearchField: "LineDays",
                ConditionType: 1,
                AndOR: "and",
                ListSearchValue: [
                    {
                        ItemValue: pickerLineDays.value[0]
                    }
                ]
            };
            v_search.push(opt);
        }

        // 排序
        if (current_tabindex == 0) {
            var opt = {
                OrderName: "综合",
                OrderField: "Sort",
                OrderType: "desc"
            };
            v_order.push(opt);
        }
        else if (current_tabindex == 1) {
            var opt = {
                OrderName: "评分",
                OrderField: "ScoreSort",
                OrderType: "desc"
            };
            v_order.push(opt);
        }
        else if (current_tabindex == 2) {
            var opt = {
                OrderName: "价格",
                OrderField: "PriceOrder",
                OrderType: "asc"
            };
            v_order.push(opt);
        }

        var conditionParams = JSON.stringify({
            type: 0,
            conditionParams: {
                Page: {
                    PageSize: pagesize,
                    PageIndex: pageindex
                },
                Search: v_search,
                Order: v_order
            }
        });
        myApp.showPreloader();
        $$.ajax({
            url: ISS_Constants.Url.defaulturl + ISS_Constants.serviceName.LINE,
            data: { content: conditionParams },
            dataType: "jsonp",
            crossDomain: true,
            success: function (data, status) {
                myApp.hidePreloader();
                data = JSON.parse(data);
                loading=false;
                if (current_tabindex == 0 && index_tab1 == 1) {
                    $$("#sub_tab1 .content-block ul").children("li").remove();
                }
                if (current_tabindex == 1 && index_tab2 == 1) {
                    $$("#sub_tab2 .content-block ul").children("li").remove();
                }
                if (current_tabindex == 2 && index_tab3 == 1) {
                    $$("#sub_tab3 .content-block ul").children("li").remove();
                }

                if (data && data.status == "0" && data.results.length > 0) {

                    for (var i = 0; i < data.results.length; i++) {
                        if (data.results[i].getImage && (data.results[i].getImage.smallImageFrontUrl == undefined ||
                            data.results[i].getImage.smallImageFrontUrl == null || data.results[i].getImage.smallImageFrontUrl == "")) {
                            data.results[i].getImage.smallImageFrontUrl = NoPicture();
                        }
                        data.results[i].distance = ISS.utils.toFixed(data.results[i].distance, 2);

                        //出发地点添加 出发  两个字
                        // if (!data.results[i].departLoc.endWith("出发")) {
                        //     data.results[i].departLoc += "出发";
                        // }
                    };

                    var searchTemplate = $$('#template-line-tab2').html();
                    if (searchTemplate) {
                        var compiledTemplate = Template7.compile(searchTemplate);
                        var html = compiledTemplate(data);
                        if (current_tabindex == 0) $$("#sub_tab1 .content-block ul").append(html);
                        else if (current_tabindex == 1) $$("#sub_tab2 .content-block ul").append(html);
                        else if (current_tabindex == 2) $$("#sub_tab3 .content-block ul").append(html);
                        flag_InfiniteScroll = flag_needScroll = true;
                    }

                    if (current_tabindex == 0 && $$("#sub_tab1 .content-block ul li").length >= data.total) {
                        // 删除加载提示符
                        $$('.infinite-scroll-preloader1').remove();
                        // 加载完毕，则注销无限加载事件，以防不必要的加载
                        myApp.detachInfiniteScroll($$('.infinite-scroll'));
                    }
                    else if (current_tabindex == 1 && $$("#sub_tab2 .content-block ul li").length >= data.total) {
                        // 删除加载提示符
                        $$('.infinite-scroll-preloader2').remove();
                        // 加载完毕，则注销无限加载事件，以防不必要的加载
                        myApp.detachInfiniteScroll($$('.infinite-scroll'));
                    }
                    else if (current_tabindex == 2 && $$("#sub_tab3 .content-block ul li").length >= data.total) {
                        // 删除加载提示符
                        $$('.infinite-scroll-preloader3').remove();
                        // 加载完毕，则注销无限加载事件，以防不必要的加载
                        myApp.detachInfiniteScroll($$('.infinite-scroll'));
                    }
                }
                else {
                    // 删除加载提示符
                    myApp.detachInfiniteScroll($$('.infinite-scroll'));
                    if (current_tabindex == 0) {
                        $$('.infinite-scroll-preloader1').remove();
                        if (data.total == 0)
                            $$("#sub_tab1 .content-block").html(ISS_Element.DIV.noAnswer);
                            $$("#sub_tab1 .noAnswer").on("click", function () {
                                index_tab1=1;
                             
                                LoadLineAll(index_tab1, current_tabindex);
                            });
                    }
                    else if (current_tabindex == 1) {
                        $$('.infinite-scroll-preloader2').remove();
                        if (data.total == 0)
                            $$("#sub_tab2 .content-block").html(ISS_Element.DIV.noAnswer);
                            $$("#sub_tab2 .noAnswer").on("click", function () {
                                index_tab2=1;
                               
                                LoadLineAll(index_tab2, current_tabindex);
                            });
                    } 
                    else if (current_tabindex == 2) {
                        $$('.infinite-scroll-preloader3').remove();
                        if (data.total == 0)
                            $$("#sub_tab3 .content-block").html(ISS_Element.DIV.noAnswer);
                            $$("#sub_tab3 .noAnswer").on("click", function () {
                                index_tab3=1;
              
                                LoadLineAll(index_tab3, current_tabindex);
                            });
                    }
                }

            },
            error: function (xhr, status) {
                myApp.hidePreloader();
                myApp.alert("服务器连接失败！");
                loading=false;
             }
        });
    }

    // 加载flag
    var loading = false;
    // 注册无限加载'infinite'事件处理函数
    $$('.infinite-scroll').on('infinite', function () {

        // 如果正在加载，则退出
        if (loading) return;

        // 设置flag
        loading = true;

        // 模拟1s的加载过程
        setTimeout(function () {

            if (current_tabindex == 0) {
                index_tab1++;
                LoadLineAll(index_tab1, size);
            }
            else if (current_tabindex == 1) {
                index_tab2++;
                LoadLineAll(index_tab2, size);
            }
            else if (current_tabindex == 2) {
                index_tab3++;
                LoadLineAll(index_tab3, size);
            }
        }, 1000);
    }); // end infinite

    //查询条件
    $$(".view-right a.close-panel").on("click", function () {
        myApp.attachInfiniteScroll($$('.infinite-scroll'));
        $$("#sub_tab1 .content-block ul").children("li").remove();
        $$("#sub_tab2 .content-block ul").children("li").remove();
        $$("#sub_tab3 .content-block ul").children("li").remove();
        $$(".noAnswer").remove();

        flag_InfiniteScroll = false;
        flag_needScroll = true;
        index_tab1 = index_tab2 = index_tab3 = 1;
        if (current_tabindex == 0) LoadLineAll(index_tab1, size);
        else if (current_tabindex == 1) LoadLineAll(index_tab2, size);
        else if (current_tabindex == 2) LoadLineAll(index_tab3, size);

    });

    //价格 评价切换
    $$(".subnavbar").on("click", "a", function () {
        $$('.infinite-scroll').scrollTop(0);
        current_tabindex = $$(this).index();
        myApp.attachInfiniteScroll($$('.infinite-scroll'));

        flag_InfiniteScroll = true;
        flag_needScroll = false;
        if (current_tabindex == 0 && $$("#sub_tab1 .content-block ul").children("li").length == 0) {
            LoadLineAll(index_tab1, size);
        }
        else if (current_tabindex == 1 && $$("#sub_tab2 .content-block ul").children("li").length == 0) {
            LoadLineAll(index_tab2, size);
        }
        else if (current_tabindex == 2 && $$("#sub_tab3 .content-block ul").children("li").length == 0) {
            LoadLineAll(index_tab3, size);
        }
    });
});

/* 线路详情  */
var contactsCallback_lineDetail = myApp.onPageInit('lineDetail', function (page) {
    var linedetail_guid = ISS.utils.getParameter("linedetail_guid");
    if (page != undefined) {
        linedetail_guid = page.query.linedetail_guid;
    }
    //    var v_startDate = ISS.utils.dateToStr("yyyy-MM-dd", ISS.utils.dateAdd("d", 5, new Date())); // "2015-12-01 10:22:25"; //出发日期 +4
    //    var priceToEveryday = {

    //    };

    // 加载数据
    loadlineDetail();
    function loadlineDetail() {
        var _content = JSON.stringify({
            type: 1,
            Code: linedetail_guid,
            PlayDate: ISS.utils.dateToStr("yyyy-MM-dd hh:mm:ss", new Date())
        });
        myApp.showPreloader();
        $$.ajax({
            url: ISS_Constants.Url.defaulturl + ISS_Constants.serviceName.LINE,
            data: { "content": _content },
            crossDomain: true,
            dataType: "jsonp",
            method: "POST",
            success: function (sdata, status) {
                try {
                    var data = JSON.parse(sdata);
                    data = data.results;
                    var searchTemplate = $$('#line_detail_page #template_line_detail').html();
                    if (searchTemplate) {
                        //处理主图片
                        if (data.getImage == null || data.getImage == undefined || data.getImage.imageList.length == 0) data.getImage = { imageList: [{ middleImgSrc: NoPicture() }] }

                        //处理行程
                        if (data.getLineDaysInfo != null && data.getLineDaysInfo.length && data.getLineDaysInfo.length > 0) {
                            for (var i = 0; i < data.getLineDaysInfo.length; i++) {
                                var hotel = [];
                                var hotelcode = "";
                                var attraction = [];
                                var attractioncode = "";
                                if (data.getLineDaysInfo[i].lineDaysDetailInfoList != null && data.getLineDaysInfo[i].lineDaysDetailInfoList.length && data.getLineDaysInfo[i].lineDaysDetailInfoList.length > 0) {
                                    for (var j = 0; j < data.getLineDaysInfo[i].lineDaysDetailInfoList.length; j++) {
                                        var days = data.getLineDaysInfo[i].lineDaysDetailInfoList[j];
                                        if (days.getRelationAttraction != null) {
                                            if (attractioncode.indexOf(days.getRelationAttraction.code) <= -1) {
                                                attraction.push({ code: days.getRelationAttraction.code, cnName: days.getRelationAttraction.cnName });
                                                attractioncode += days.getRelationAttraction.code + ",";
                                            }
                                        }
                                        if (days.getRelationHotel != null) {
                                            if (hotelcode.indexOf(days.getRelationHotel.code) <= -1) {
                                                hotel.push({ code: days.getRelationHotel.code, cnName: days.getRelationHotel.cnName });
                                                hotelcode += days.getRelationHotel.code + ",";
                                            }
                                        }
                                    }
                                }
                                data.getLineDaysInfo[i].attraction = attraction;
                                data.getLineDaysInfo[i].hotel = hotel;
                            }
                        }

                        //判断是否预订
                        if (data.isReserve == "0") {//不能预订
                            data.IsBooking = false;
                        } else {
                            data.IsBooking = true;
                        }

                        //处理模板
                        var compiledTemplate = Template7.compile(searchTemplate);
                        var html = compiledTemplate(data);
                        $$("#line_detail_page .page-content").html(html);


                        //头部图片滑动
                        if (data.getImage.imageList.length > 1) {
                            var mySwiper = new Swiper('.swiper-container', {
                                // pagination: '.swiper-pagination',
                                autoplay: 5000,
                                speed: 300
                            });
                            var ImageList = [];
                            for (var i = 0; i < data.getImage.imageList.length; i++) {
                                ImageList[i] = data.getImage.imageList[i].middleImgSrc;
                            }
                            iss_localStorage.set("yuqing_ImgList", ImageList);
                        }

                        //加载日历
                        var getLinesDayPrice = data.getLinesDayPrice;
                        if (getLinesDayPrice != undefined && getLinesDayPrice != "" && getLinesDayPrice.length && getLinesDayPrice.length > 0) {
                            loadDatepicker("a.line-date p", data.salePrice, getLinesDayPrice);
                        }
                        else {
                            loadDatepicker("a.line-date p", data.salePrice);
                        }
                    }

                    myApp.hidePreloader();

                } catch (ex) {
                    myApp.hidePreloader();
                }
            },
            error: function (xhr, status) {
                myApp.hidePreloader();
            }
        });
        $$("#line_detail_page .page-content").on("click", "div.swiper-container", function () {
            mainView.router.loadPage({ url: $$(this).attr("data-href"), reload: false });
            // window.location.href=$$(this).attr("data-href");
        })
    }

    //加载日历
    function loadDatepicker(inpuid, salePrice, getLinesDayPrice) {
        var monthNames = ['1月', '2月', '03月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'];
        var calendarInline = myApp.calendar({
            input: inpuid,
            value: [new Date()],
            minDate: GetDateStr(0),
            maxDate: addmulMonth(GetDateStr(0), 3),
            monthNames: monthNames,
            dateFormat: 'yyyy-mm-dd',
            dayNamesShort: ['日', '一', '二', '三', '四', '五', '六'],
            toolbarTemplate:
            '<div class="toolbar calendar-custom-toolbar">' +
            '<div class="toolbar-inner">' +
            '<div class="left">' +
            '<a href="#" class="link icon-only"><i class="icon icon-back"></i></a>' +
            '</div>' +
            '<div class="center"></div>' +
            '<div class="right">' +
            '<a href="#" class="link icon-only"><i class="icon icon-forward"></i></a>' +
            '</div>' +
            '</div>' +
            '</div>',
            onOpen: function (p) {
                $$('.calendar-custom-toolbar .center').text(p.currentYear + "年" + monthNames[p.currentMonth]);
                $$('.calendar-custom-toolbar .left .link').on('click', function () {
                    calendarInline.prevMonth();
                });
                $$('.calendar-custom-toolbar .right .link').on('click', function () {
                    calendarInline.nextMonth();
                });
            },
            onMonthYearChangeStart: function (p) {
                $$('.calendar-custom-toolbar .center').text(p.currentYear + "年" + monthNames[p.currentMonth]);
            },
            onDayClick: function (p, dayContainer, year, month, day) {
                var date = year + "-" + checkTime(parseInt(month) + 1) + "-" + checkTime(day);
                $$("a.line-date p").html(date);
                $$("#line_detail_page .btn-booking").attr("data-href", "lineBooking.html?date=" + date + "&linedetail_guid=" + linedetail_guid);
                //处理日期价格
                if (getLinesDayPrice != undefined) {
                    var hasprice = false;
                    for (var i = 0; i < getLinesDayPrice.length; i++) {
                        if (getLinesDayPrice[i].changeTime == year + "-" + checkTime(parseInt(month) + 1) + "-" + checkTime(day)) {
                            $$("#line_detail_page .line-price span.price").html(getLinesDayPrice[i].newSalePrice);
                            hasprice = true; break;
                        }
                    }
                    if (!hasprice) {
                        $$("#line_detail_page .line-price span.price").html(salePrice);
                    }
                }
            }
        });

        var myDate = new Date();
        var nowy = myDate.getFullYear(); //当前年
        var nowm = myDate.getMonth() + 1; //当前月
        var nowd = myDate.getDate(); //当前日
        $$("a.line-date p").html(nowy + "-" + checkTime(nowm) + "-" + checkTime(nowd));
        $$("#line_detail_page .btn-booking").attr("data-href", "lineBooking.html?date=" + nowy + "-" + checkTime(nowm) + "-" + checkTime(nowd) + "&linedetail_guid=" + linedetail_guid);
    }

    //预订按钮
    $$("#line_detail_page .page-content").on("click", "a.btn-booking[href='#']", function (e) {
        //取消原有跳转事件
        e.stopPropagation();
        //保存当前控件
        var mythis = $$(this);
        //跳转判断
        CheckPopLogin(function () {
            //window.location.href = mythis.attr("data-href");
            mainView.router.loadPage({ url: mythis.attr("data-href"), reload: false });
        });
    })
});

/* 线路预订  */
var contactsCallback_lineBooking = myApp.onPageInit('lineBooking', function (page) {
    var date = ISS.utils.getParameter("date");
    var linedetail_guid = ISS.utils.getParameter("linedetail_guid");
    if (page != undefined) {
        date = page.query.date;
        linedetail_guid = page.query.linedetail_guid;
    }
    var _salePrice; //销售价格
    var _yfsalePrice; //预付价格
    var _travelCode; //商铺编号

    //加载线路信息
    loadLine();
    function loadLine() {
        var _content = JSON.stringify({
            type: 1,
            Code: linedetail_guid,
            PlayDate: date
        });
        myApp.showPreloader();
        $$.ajax({
            url: ISS_Constants.Url.defaulturl + ISS_Constants.serviceName.LINE,
            data: { "content": _content },
            crossDomain: true,
            dataType: "jsonp",
            method: "POST",
            success: function (sdata, status) {
                try {
                    var data = JSON.parse(sdata);
                    data = data.results;
                    //处理数据
                    $$("#linebooking_page .booking-tit").html(data.cnName); //线路名
                    $$("#linebooking_page #begindate").attr("date", date); //出发日期

                    $$("#linebooking_page .original-price span").html(data.settlementPrice); //挂牌价


                    //$$("#linebooking_page .single-price span.wg").html(data.salePrice); //销售价
                    $$("#linebooking_page .single-price span.yd").html(parseFloat(data.businessDeposit) + parseFloat(data.deposit)); //预付价
                    _yfsalePrice = parseFloat(data.businessDeposit) + parseFloat(data.deposit);
                    $$("#linebooking_page .tip").html("特别声明：" + data.specialNote);
                    _travelCode = data.travelCode;


                    var getLinesDayPrice = data.getLinesDayPrice;
                    //销售价
                    if (getLinesDayPrice != undefined) {
                        var hasprice = false;
                        for (var i = 0; i < getLinesDayPrice.length; i++) {
                            if (getLinesDayPrice[i].changeTime == date) {
                                $$("#linebooking_page .single-price span.wg").html(getLinesDayPrice[i].newSalePrice);
                                _salePrice = getLinesDayPrice[i].newSalePrice;
                                hasprice = true; break;
                            }
                        }
                        if (!hasprice) {
                            $$("#linebooking_page .single-price span.wg").html(data.salePrice);
                            _salePrice = data.salePrice;
                        }
                    }

                    //加载日历
                    if (getLinesDayPrice != undefined && getLinesDayPrice != "" && getLinesDayPrice.length && getLinesDayPrice.length > 0) {
                        loadDatepicker("#begindate", data.salePrice, getLinesDayPrice);
                    }
                    else {
                        loadDatepicker("#begindate", data.salePrice);
                    }

                    //计算金额
                    SumPrice();

                    myApp.hidePreloader();
                } catch (ex) {
                    myApp.hidePreloader();
                }
            },
            error: function (xhr, status) {
                myApp.hidePreloader();
            }
        });
    }


    function loadDatepicker(inpuid, salePrice, getLinesDayPrice) {
        var monthNames = ['1月', '2月', '03月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'];
        var calendarInline = myApp.calendar({
            input: inpuid,
            value: [date],
            minDate: GetDateStr(0),
            maxDate: addmulMonth(GetDateStr(0), 3),
            monthNames: monthNames,
            dateFormat: 'yyyy-mm-dd',
            dayNamesShort: ['日', '一', '二', '三', '四', '五', '六'],
            toolbarTemplate:
            '<div class="toolbar calendar-custom-toolbar">' +
            '<div class="toolbar-inner">' +
            '<div class="left">' +
            '<a href="#" class="link icon-only"><i class="icon icon-back"></i></a>' +
            '</div>' +
            '<div class="center"></div>' +
            '<div class="right">' +
            '<a href="#" class="link icon-only"><i class="icon icon-forward"></i></a>' +
            '</div>' +
            '</div>' +
            '</div>',
            onOpen: function (p) {
                $$('.calendar-custom-toolbar .center').text(p.currentYear + "年" + monthNames[p.currentMonth]);
                $$('.calendar-custom-toolbar .left .link').on('click', function () {
                    calendarInline.prevMonth();
                });
                $$('.calendar-custom-toolbar .right .link').on('click', function () {
                    calendarInline.nextMonth();
                });
            },
            onMonthYearChangeStart: function (p) {
                $$('.calendar-custom-toolbar .center').text(p.currentYear + "年" + monthNames[p.currentMonth]);
            },
            onDayClick: function (p, dayContainer, year, month, day) {
                var date = year + "-" + checkTime(parseInt(month) + 1) + "-" + checkTime(day);
                $$("#begindate").attr("date", date).html(year + "年 " + checkTime(parseInt(month) + 1) + "月 " + checkTime(day) + "日" + '<i class="iconfont icon-jiantou"></i>');

                //处理日期价格
                if (getLinesDayPrice != undefined) {
                    var hasprice = false;
                    for (var i = 0; i < getLinesDayPrice.length; i++) {
                        if (getLinesDayPrice[i].changeTime == year + "-" + checkTime(parseInt(month) + 1) + "-" + checkTime(day)) {
                            $$("#linebooking_page .single-price span.wg").html(getLinesDayPrice[i].newSalePrice);
                            _salePrice = getLinesDayPrice[i].newSalePrice;
                            hasprice = true; break;
                        }
                    }
                    if (!hasprice) {
                        $$("#linebooking_page .single-price span.wg").html(salePrice);
                        _salePrice = salePrice;
                    }
                }
                //计算金额
                SumPrice()
            }
        });
        var myDate = ISS.utils.strToDate(date);
        var nowy = myDate.getFullYear(); //当前年
        var nowm = myDate.getMonth() + 1; //当前月
        var nowd = myDate.getDate(); //当前日
        $$("#begindate").attr("date", date).html(nowy + "年 " + checkTime(parseInt(nowm)) + "月 " + checkTime(nowd) + "日" + '<i class="iconfont icon-jiantou"></i>');
    }


    //计算金额
    function SumPrice() {
        var saleprice = $$("#linebooking_page span.wg").html()//网购价
        var listingPrice = $$("#linebooking_page .original-price span").html()//市场价
        var yfprice = $$("#linebooking_page .single-price span.yd").html(); //预付价

        var orderNumber = parseInt($$("div.num span").html()); //数量
        var sum_money = ISS.utils.toFixed(parseFloat(saleprice) * orderNumber); //总全款
        var sum_yfmoney = ISS.utils.toFixed(parseFloat(yfprice) * orderNumber); //总预付款

        var one_thrift_money = parseFloat(listingPrice - saleprice); //差价
        var sum_thrift_money = ISS.utils.toFixed(one_thrift_money * orderNumber); //总差价

        var paytype = $$("input[type='radio']:checked").val();
        if (paytype == "yf") {
            //预付款
            $$("#linebooking_page div.sum-price span.totle").html(sum_yfmoney);
            $$("#linebooking_page .totle_txt").html("合计预付款");
        } else {
            //全款
            $$("#linebooking_page div.sum-price span.totle").html(sum_money);
            $$("#linebooking_page .totle_txt").html("合计全款");
        }



        $$("#linebooking_page div.sum-price span.thrift").html(sum_thrift_money);
    }

    //加
    $$("div.num a.jia1").click(function () {
        if ($$(this).hasClass("unable")) return;
        var num = $$("div.num span").html();
        num = parseInt(num) + 1;
        if (num >= 99) $$(this).addClass("unable");
        $$("div.num span").html(num);
        if (num > 1) $$("div.num a.jian1").removeClass("unable");
        SumPrice();
    })
    //减
    $$("div.num a.jian1").click(function () {
        if ($$(this).hasClass("unable")) return;
        var num = $$("div.num span").html();
        num = parseInt(num) - 1;
        if (num <= 1) $$(this).addClass("unable");
        if (num < 99) $$("div.num a.jia1").removeClass("unable");
        $$("div.num span").html(num);
        SumPrice();
    })

    //付款方式
    $$("input[type='radio']").change(function () {
        SumPrice();
    });



    var _userID = iss_localStorage.get("yuqing_appUserId"); // 全局变量


    //加载用户
    loadUser(_userID);
    function loadUser(userID) {
        var _content = JSON.stringify({
            type: 13,
            user: {
                ID: userID,
                PhoneNumber: ""
            }
        });
        $$.ajax({
            url: ISS_Constants.Url.defaulturl + ISS_Constants.serviceName.USERINFO,
            data: { "content": _content },
            crossDomain: true,
            method: "POST",
            success: function (data, status) {
                data = JSON.parse(data);
                if (data && data.status == "0") {
                    $$("#linebooking_page #name").val(data.results.name); //联系人
                    $$("#linebooking_page #telephone").val(data.results.phoneNumber); //联系电话
                    $$("#linebooking_page #card").val(data.results.cardNo); //身份证号
                }
                else {
                    myApp.alert('获取用户失败!');
                }
            },
            error: function (xhr, status) {
                myApp.alert('获取用户失败!');
            }
        });

    }
    $$("input[name='my-checkbox']").change(function () {
        if ($$(this).is(':checked')) {
            $$("#btnsubOrder").removeAttr("disabled");
        }
        else {
            $$("#btnsubOrder").attr("disabled", "disabled");
        }
    })


    //提交订单
    $$("#btnsubOrder").click(function () {
        //        mainView.router.loadPage({ url: "linePay.html?OrderNo=" + "201606220325580088830" + "&OrderName=" + $$("#linebooking_page .booking-tit").html(), reload: false });
        //        return;

        var _name = $$(".booking-info #name").val(); //联系人
        var _telephone = $$(".booking-info #telephone").val(); //联系电话
        var _card = $$(".booking-info #card").val(); //身份证号
        var _recommendcode = $$(".booking-info #recommendcode").val(); //推荐码

        var _orderNumber = $$("div.num span").html();
        var _sumPrice = parseFloat(_salePrice) * parseInt(_orderNumber); //全款
        var _yfsumPrice = parseFloat(_yfsalePrice) * parseInt(_orderNumber); //预付款

        var paytype = $$("input[type='radio']:checked").val();
        if (paytype == "qk") { _yfsumPrice = "0"; }

        if (_name == '') {
            myApp.alert("请填写您的姓名");
            return;
        }
        if (_card == '') {
            myApp.alert("请填写您的身份证号");
            return;
        }
        var reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
        if (reg.test(_card) === false) {
            myApp.alert('身份证输入不合法!');
            return;
        }
        if (_telephone == '') {
            myApp.alert("请填写您的手机号码");
            return;
        }
        if (!/^((1[3-9])+\d{9})$/.test(_telephone)) {
            myApp.alert("请填写正确的手机号码！");
            return;
        }
        var _content = JSON.stringify({
            orderSubmitEntity: {
                PayType: 2, //支付方式
                Phone: _telephone,
                UserID: _userID,
                Source: 2, //订单来源
                TotalSalePrice: _sumPrice, //订单总价
                OrderShopEntity: [
                    {
                        ShopType: 8, //旅行社签约类型
                        UserID: _userID,
                        ShopCode: _travelCode, //商铺编号
                        OrderName: $$("#linebooking_page .booking-tit").html(), //订单名称
                        OrderType: 2, //订单类型
                        Leavemsg: "", //店铺留言备注
                        Person: _name, //预订人
                        Mail: "",
                        Phone: _telephone, //手机
                        Tel: _telephone, //电话
                        RecommendCode: _recommendcode, //推荐码
                        IDCard: _card, //身份证号码
                        OrderProductEntity: [
                            {
                                AdvancePay: _yfsumPrice, //定金
                                DepartDay: $$("#begindate").attr("date"), //发团日期
                                AdvanceBusinessPay: 0, //商家定金
                                Absence: 0, //缺席人数
                                ProductCode: linedetail_guid, //线路编号
                                OrderNumber: _orderNumber,
                                SalePrice: _salePrice//线路价格
                            }
                        ]
                    }
                ]
            },
            type: 23
        });

        myApp.showPreloader();
        $$.ajax({
            url: ISS_Constants.Url.defaulturl + ISS_Constants.serviceName.CREATEORDER,
            data: { "content": _content },
            crossDomain: true,
            method: "POST",
            success: function (data, status) {
                myApp.hidePreloader();
                data = JSON.parse(data);
                if (data && data.status == "0") {
                    mainView.router.loadPage({ url: "linePay.html?OrderNo=" + data.results + "&OrderName=" + name + "&SumPrice=" + _sumPrice, reload: false });
                    return;
                }
                else {
                    myApp.hidePreloader();
                    myApp.alert('提交订单失败!');
                }
            },
            error: function (xhr, status) {
                myApp.hidePreloader();
                myApp.alert('提交订单失败!');
            }
        });
    }) // end click
    //    var _content = JSON.stringify({
    //        type: 1,
    //        Code: ISS.utils.getParameter("route")!="" ||ISS.utils.getParameter("route")!= null? ISS.utils.getParameter("route"):page.query.route,
    //        PlayDate: ISS.utils.dateToStr("yyyy-MM-dd hh:mm:ss", new Date())
    //    })
    //    $$.ajax({
    //        url: ISS_Constants.Url.defaulturl + ISS_Constants.serviceName.LINE,
    //        data: { "content": _content },
    //        crossDomain: true,
    //        dataType: "jsonp",
    //        method: "POST",
    //        success: function (sdata, status) {
    //            var data = JSON.parse(sdata);
    //            if (data && data.status == "0" && data.results) {
    //                data = data.results;
    //                var searchTemplate = $$('#template_line_order').html();
    //                if (searchTemplate) {
    //                    var _orderNum = 1;
    //                    var compiledTemplate = Template7.compile(searchTemplate);
    //                    var html = compiledTemplate(data);
    //                    $$("#lineBooking_page .page-content").html(html);
    //                    //预定时候的价格和日期
    //                    var qcudate = ISS.utils.getParameter("cudate")!="" ||ISS.utils.getParameter("cudate")!= null? ISS.utils.getParameter("cudate"):page.query.cudate;
    //                    var qcup = ISS.utils.getParameter("cup")!="" ||ISS.utils.getParameter("cup")!= null? ISS.utils.getParameter("cup"):page.query.cup;
    //                    var qbop = ISS.utils.getParameter("qbop")!="" ||ISS.utils.getParameter("bop")!= null? ISS.utils.getParameter("bop"):page.query.cup;
    //                    $$("#lineTime").html("出发时间："+  qcudate)
    //                    $$("#linePrice").html("单价：¥&nbsp;"+ qcup)
    //                    $$("#bookingPrice").html("预订价:¥&nbsp;" + qbop)
    //                    $$("#picker_lineBooking_orderNumber").val(_orderNum);
    //                    $$("#finalPrice").html(qcup);
    //                    $$("#calendar-date-format-line-order").val(qcudate)
    //                    $$("#calendar-date-format-line-order").attr('placeholder', qcudate)
    //                    
    //                     // 预订数量
    //                    var pickerLineNum = myApp.picker({
    //                        input: '#lineBooking_page #picker_lineBooking_orderNumber',
    //                        rotateEffect: true,
    //                        toolbarTemplate:
    //                        '<div class="toolbar theme-red">' +
    //                            '<div class="toolbar-inner">' +
    //                                '<div class="left"></div>' +
    //                                '<div class="right">' +
    //                                    '<a href="#" class="link close-picker">关闭</a>' +
    //                                '</div>' +
    //                            '</div>' +
    //                        '</div>',
    //                        formatValue: function (picker, values) {
    //                            return values[1];
    //                        },
    //                        cols: [
    //                            {
    //                                textAlign: 'left',
    //                                values: ['数量'],
    //                            },
    //                            {
    //                                values: (function () {
    //                                    var arr = [];
    //                                    for (var i = 1; i <= 99; i++) { arr.push(i); }
    //                                    return arr;
    //                                })(),
    //                                onChange: function (picker, value) {
    //                                    SumPrice();
    //                                },
    //                                onClose: function (picker) {

    //                                }
    //                            }
    //                        ]
    //                    });

    //                    // 日历控件
    //                    DatepickerFunXianLu('#calendar-date-format-line-order', function (picker) {
    //                        var value = picker.value[0];
    //                        var date = new Date(value);
    //                        Y = date.getFullYear() + '-';
    //                        M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    //                        D = date.getDate();
    //                        if (D < 10)
    //                            D = "0" + D;
    //                        var finalValue = Y + M + D;
    //                        //var finalPrice = priceToEveryday[finalValue];
    //                        // var bookingfinalPrice = bookingpriceToEveryday[finalValue];
    ////                        if (finalPrice != undefined) {
    ////                            document.getElementById("line-price").value = finalPrice;
    ////                        }
    ////                        if (bookingfinalPrice != undefined) {
    ////                            document.getElementById("booking-price").innerText = bookingfinalPrice;
    ////                        }
    ////                        else {
    ////                            document.getElementById("line-price").value = "暂无价格";
    ////                            document.getElementById("line-price").value = 0;
    ////                        }
    //                    });

    //                     // 计算价格
    //                    function SumPrice() {
    //                        var orderNumber = $$("#lineBooking_page #picker_lineBooking_orderNumber").val();
    //                        if (pickerLineNum && pickerLineNum.cols.length > 0) {
    //                            orderNumber = parseInt(pickerLineNum.cols[1].value);
    //                        }
    //                        var linePrice = parseFloat($$("#lineBooking_page #linePrice").html());
    //                        var bookingPrice = parseFloat($$("#lineBooking_page #bookingPrice").html());;
    //                        if ($$("#lineBooking_page #All")[0].checked == true)
    //                            $$("#lineBooking_page #totalPrice").html(orderNumber * linePrice);
    //                        else
    //                            $$("#lineBooking_page #totalPrice").html(orderNumber * bookingPrice);

    //                        $$("#lineBooking_page #finalPrice").html(orderNumber * linePrice);

    //                    };

    //                    $$("#lineBooking_page #submit").on("click", function () {
    ////                        _name = $$("#lineBooking_page #name").val();
    ////                        _orderName = _lineName;
    ////                        _telephone = $$("#lineBooking_page #telephone").val();
    ////                        _finalPrice = $$("#finalPrice").html();
    ////                        _totalPrice = $$("#totalPrice").html();
    ////                        _orderNum = $$("#lineBooking_page #picker_lineBooking_orderNumber").val();
    //        
    ////                        if (!hasUserId("请申请或绑定平台账号")) {
    ////                            myApp.loginScreen();
    ////                            return;
    ////                        }
    ////                        if (_name == "") {
    ////                            myApp.alert("请填写真实姓名！");
    ////                            return;
    ////                        }
    ////                        if (_telephone == "") {
    ////                            myApp.alert("请填写手机号！");
    ////                            return;
    ////                        }

    //                        var bs64 = new Base64();
    //                        var _userID = 21//iss_localStorage.get("yuqing_appUserId"); // 全局变量
    //                        var _payType = $$("#All")[0].checked ? 0 : 1;
    //                        //参数赋值
    //                        debugger;
    //                        var obj = new Object();
    //                        var orderSubmitEntity = new Object();
    //                        orderSubmitEntity.PayType=2//微信支付
    //                        orderSubmitEntity.Phone="18627972347"
    //                        orderSubmitEntity.UserID=1
    //                        orderSubmitEntity.Source=2//线路
    //                        orderSubmitEntity.TotalSalePrice=200;

    //                        var OrderShopEntity = new Array();
    //                        var OrderShopEntityChild =  new Object();
    //                        OrderShopEntityChild.ShopType=8;
    //                        OrderShopEntityChild.UserID=1;
    //                        OrderShopEntityChild.ShopCode="LX465500000001";
    //                        OrderShopEntityChild.OrderName="贵阳两日休闲清爽游";
    //                        OrderShopEntityChild.OrderType=2;
    //                        OrderShopEntityChild.Leavemsg="留言：";
    //                        OrderShopEntityChild.Person="客户姓名";
    //                        OrderShopEntityChild.Mail="1@qq.com";
    //                        OrderShopEntityChild.Phone="18627972347";
    //                        OrderShopEntityChild.Tel="18627972347";
    //                        OrderShopEntityChild.RecommendCode="";
    //                        OrderShopEntityChild.IDCard="";

    //                        var OrderProductEntity = new Array();
    //                        var o = new Object();
    //                        o.AdvancePay=200;//businessDeposit + deposit
    //                        o.DepartDay="2016-06-18";
    //                        o.AdvanceBusinessPay=0;
    //                        o.Absence=null;
    //                        o.ProductCode="XL4655000000010013";
    //                        o.OrderNumber=1;
    //                        o.SalePrice=200;

    //                        OrderProductEntity.push(o);
    //                        OrderShopEntityChild.OrderProductEntity=OrderProductEntity;
    //                         OrderShopEntity.push(OrderShopEntityChild);
    //                        orderSubmitEntity.OrderShopEntity=OrderShopEntity;
    //                        obj.orderSubmitEntity = orderSubmitEntity;
    //                        obj.type = 23;
    //                        //调用接口
    //                        myApp.showPreloader();
    //                        $$.ajax({
    //                            url: ISS_Constants.Url.defaulturl + ISS_Constants.serviceName.CREATEORDER,
    //                            data: {
    //                                "content": bs64.encode(JSON.stringify(obj))
    //                            },
    //                            crossDomain: true,
    //                            dataType: "json",
    //                            async: false,
    //                            success: function (data, status) {
    //                                myApp.hidePreloader();
    //                                if (data && data.result == "true") {
    //                //                    myApp.alert('提交订单成功!', '', function () {
    //                //                        mainView.router.loadPage("booking/line.html");
    //                //                    });
    //                                  _orderNo = data.OrderNo;
    //                                  UnifiedoOrder(_orderNo, _orderName, 1, 3);
    //                                }
    //                                else {
    //                                    myApp.alert('提交订单失败!');
    //                                }
    //                            },
    //                            error: function (xhr, status) {
    //                                myApp.hidePreloader();
    //                                myApp.alert("订单提交失败！");
    //                            }
    //                        });

    //                    })
    //                
    //                }
    //            }
    //        }
    //    });

});

/* 线路待付款  */
var contactsCallback_linePay = myApp.onPageInit('linePay', function (page) {
    //获取页面参数
    var OrderNo = ISS.utils.getParameter("OrderNo");
    var OrderName = ISS.utils.getParameter("OrderName");
    var SumPrice = ISS.utils.getParameter("SumPrice");
    if (page != undefined) {
        OrderNo = page.query.OrderNo;
        OrderName = page.query.OrderName;
        SumPrice = page.query.SumPrice;
    }
    $$("#linePay_page #back_booking").click(function () {
        mainView.router.back();
    })
    if (OrderNo == undefined || OrderNo == "") {
        $$("#linePay_page #faild").show();
        $$("#linePay_page #success").hide();
        return;
    }
    else {

        $$("#linePay_page #success").show();
        $$("#linePay_page #faild").hide();
    }
    var _content = JSON.stringify({
        Code: OrderNo,
        type: 1
    });
    var timer_Interval;
    myApp.showPreloader();
    $$.ajax({
        url: ISS_Constants.Url.defaulturl + ISS_Constants.serviceName.ORDERS,
        data: { "content": _content },
        crossDomain: true,
        method: "POST",
        success: function (data, status) {
            try {
                data = JSON.parse(data);
                if (data && data.status == "0") {
                    //格式化数据
                    data.results.orderSTATUSName = "";
                    if (data.results.orderSTATUS == "1") {
                        data.results.orderSTATUSName = "待确认";
                    }
                    else if (data.results.orderSTATUS == "2") {
                        data.results.orderSTATUSName = "待付款";
                    }
                    else if (data.results.orderSTATUS == "3") {
                        data.results.orderSTATUSName = "已取消";
                    }
                    else if (data.results.orderSTATUS == "4") {
                        data.results.orderSTATUSName = "已支付";
                    }
                    data.results.getLineOrderInfo[0].departDay = data.results.getLineOrderInfo[0].departDay.substring(0, 10);

                    //底部总价
                    var sumPrice = data.results.sumPrice; //总价
                    var advancePay = data.results.getLineOrderInfo[0].advancePay; //预付款
                    if (advancePay == "0") {
                        //全款方式
                        $$("#linePay_page div.sum-price span.totle").html(sumPrice);
                        $$("#linePay_page div.sum-price span.totle_txt").html("合计全款");
                        data.results.orderSTATUSName += "（全款）";
                    }
                    else {
                        //预付款方式
                        $$("#linePay_page div.sum-price span.totle").html(advancePay);
                        $$("#linePay_page div.sum-price span.totle_txt").html("合计预付款");
                        data.results.orderSTATUSName += "（预付款）";
                    }
                    var sum_thrift_money = ISS.utils.toFixed(parseFloat(data.results.totalListingPrice) - parseFloat(sumPrice)); //总差价
                    $$("#linePay_page div.sum-price span.thrift").html(sum_thrift_money);

                    //中间数据模板
                    var searchTemplate = $$('#linePay_page #template-linelpay-tab1').html();
                    if (searchTemplate) {
                        var compiledTemplate = Template7.compile(searchTemplate);
                        var html = compiledTemplate(data.results);
                        $$("#linePay_page div.card").append(html);
                    }



                    //头部倒计时
                    //var orderTime30 = ISS.utils.strToDate("2016-06-12 15:38");
                    var orderTime30 = ISS.utils.strToDate(data.results.orderTime);
                    orderTime30 = orderTime30.setMinutes(orderTime30.getMinutes() + 30);
                    if ((orderTime30 - new Date().getTime()) > 0) {
                        $$("#linePay_page #btnPayOrder").removeAttr("disabled");
                    }
                    if (timer_Interval != undefined) {
                        clearInterval(timer_Interval);
                    }
                    function timer() {
                        var ts = orderTime30 - new Date().getTime(); //计算剩余的毫秒数 
                        if (ts <= 0) {
                            $$("#linePay_page #btnPayOrder").attr("disabled", "disabled");
                            if (timer_Interval != undefined) {
                                clearInterval(timer_Interval);
                            }
                            myApp.alert('支付时间已过！', function () {
                                mainView.router.loadPage({ url: "lineDetail.html?linedetail_guid=" + data.results.getLineOrderInfo[0].productNo, reload: false });
                            })
                            return;
                        }
                        var mm = parseInt(ts / 1000 / 60 % 60, 10); //计算剩余的分钟数  
                        var ss = parseInt(ts / 1000 % 60, 10); //计算剩余的秒数  
                        mm = checkTime(mm);
                        ss = checkTime(ss);
                        $$("#linePay_page b.min").html(mm);
                        $$("#linePay_page b.sec").html(ss);
                    }
                    timer_Interval = setInterval(timer, 1000);
                    myApp.hidePreloader();

                }
                else {
                    myApp.hidePreloader();
                    myApp.alert('参数错误!');
                }
            } catch (ex) {
                myApp.hidePreloader();
            }
        },
        error: function (xhr, status) {
            myApp.hidePreloader();
            myApp.alert('参数错误!');
        }
    });


    function checkTime(k) {
        if (k < 10) {
            k = "0" + k;
        }
        return k;
    }

    $$("#linePay_page #btn_back").click(function () {
        if (timer_Interval != undefined) {
            clearInterval(timer_Interval);
        }
    })

    //支付
    var IsPaying = false;
    $$("#linePay_page #btnPayOrder").click(function () {
        if (!IsPaying) {
            //标识正在支付
            IsPaying = true;
            //订单号 --- 订单名称 --- 价格 --- 类型：1：酒店 2：线路 3：门票 --- 回调函数
            WxPay.utils.UnifiedoOrder(OrderNo, '1', function (result) {
                //标识支付完成
                IsPaying = false;
                mainView.router.loadPage({ url: "payResult.html?result=" + result + "&type=2", reload: false })
            });
        }
    })
});

/* 初始化  */
function initData() {
    var href = window.location.href;
    if (href.indexOf(line) > -1) {
        contactsCallback_line.trigger();
    }
    else if (href.indexOf(lineDetail) > -1) {
        contactsCallback_lineDetail.trigger();
    }
    else if (href.indexOf(lineBooking) > -1) {
        contactsCallback_lineBooking.trigger();
    }
    else if (href.indexOf(linePay) > -1) {
        contactsCallback_linePay.trigger();
    }
    else if (href.indexOf(tour_line) > -1) {
        contactsCallback_line.trigger();
    }
    else if (href.indexOf(tour_line_detail) > -1) {
        contactsCallback_lineDetail.trigger();
    }
}

initData();


function checkTime(k) {
    if (k.toString().length == 1) {
        k = "0" + k;
    }
    return k;
}

function GetDateStr(AddDayCount) {
    var dd = new Date();
    dd.setDate(dd.getDate() + AddDayCount); //获取AddDayCount天后的日期 
    var y = dd.getFullYear();
    var m = dd.getMonth() + 1; //获取当前月份的日期 
    var d = dd.getDate();
    return y + "-" + m + "-" + d;
}

function addmulMonth(dtstr, n) {   // n个月后 
    var s = dtstr.split("-");
    var yy = parseInt(s[0]); var mm = parseInt(s[1] - 1); var dd = parseInt(s[2]);
    var dt = new Date(yy, mm, dd);
    dt.setMonth(dt.getMonth() + n);
    if ((dt.getYear() * 12 + dt.getMonth()) > (yy * 12 + mm + n)) {
        dt = new Date(dt.getYear(), dt.getMonth(), 0);
    }
    var year = dt.getFullYear();
    var month = dt.getMonth() + 1;
    var days = dt.getDate();
    var dd = year + "-" + month + "-" + days;
    return dd;
}

//发送验证码
$$("#btnSendCode").on("click", function () {
    var appAccount = iss_localStorage.get("yuqing_appAccount");
    var phone = $$("#phone").val();

    //等待层
    myApp.showPreloader();
    SendVerificationCode(appAccount, phone, function (result) {
            if (result == "-1") {
                myApp.alert("请填写正确的手机号码");
                myApp.hidePreloader();
            } else if (result == "0") {
                myApp.alert("获取验证码失败");
                myApp.hidePreloader();
            } else if (result == "1") {
                //禁用获取验证码按钮
                $$("#btnSendCode").attr("disabled", true);
                myApp.hidePreloader();
            }
        }
    );
})

//登录
$$("#btnRegister").on("click", function () {
    var appAccount = iss_localStorage.get("yuqing_appAccount");
    var phone = $$("#phone").val();
    var vericode = $$("#vericode").val();

    //验证手机号格式
    if (!ISS.utils.CheckPhone(phone)) {
        myApp.alert("请填写正确的手机号码");
        return;
    }
    //验证验证码输入
    if (vericode == "") {
        myApp.alert("请输入验证码");
        return;
    }

    //打开等待层
    myApp.showPreloader();
    //验证手机号+验证码
    var phoneNumber = CheckVerificationCode(appAccount, phone, vericode);
    //验证成功，根据手机号到门户获取用户信息
    if (phoneNumber && phoneNumber != null) {
        var userInfo = GetUserInfoByPhone(phoneNumber);
        //获取失败
        if (userInfo == null) {
            //注册用户
            userInfo = CreateUser(phoneNumber);
        }
        if (userInfo && userInfo != null) {
            //同步WX_User 的 UserId
            var updateResult = UpdateUserId(userInfo.ID, "");
            //同步WAP_User 的信息
            var saveResult = SaveWapUser(userInfo);
            //正常流程-----
        }
    } else {
        myApp.alert("验证码错误");
    }
    //关闭等待层
    myApp.hidePreloader();
    //关闭登录窗口
    myApp.closeModal(loginScreen);
})